#! /usr/bin/env python
import urllib2

BASE_URL = 'http://www.7manba.com:8000'

_hoppish = {
    'connection': 1, 'keep-alive': 1, 'proxy-authenticate': 1,
    'proxy-authorization': 1, 'te': 1, 'trailers': 1, 'transfer-encoding': 1,
    'upgrade': 1
}.__contains__


def is_hop_by_hop(header_name):
    """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header"""
    return _hoppish(header_name.lower())


def application(environ, start_response):
    # Sorting and stringifying the environment key, value pairs
    raw_uri = '%s?%s' % (environ.get('PATH_INFO'), environ.get('QUERY_STRING'))
    method = environ.get('REQUEST_METHOD')
    data = None
    if method == 'POST':
        try:
            request_body_size = int(environ.get('CONTENT_LENGTH', 0))
        except (ValueError):
            request_body_size = 0
        data = environ.get('wsgi.input').read(request_body_size)
    request = urllib2.Request(BASE_URL + raw_uri, data)
    try:
        response = urllib2.urlopen(request)
    except Exception, e:
        response = e

    headres = []
    for name, val in response.headers.dict.items():
        if not is_hop_by_hop(name):
            headres.append((name, val))

    reason = str(response.code) + ' ' + response.msg
    start_response(reason, headres)

    return [response.read()]


if __name__ == '__main__':
    # Our tutorial's WSGI server
    from wsgiref.simple_server import make_server
    # Instantiate the WSGI server.
    # It will receive the request, pass it to the application
    # and send the application's response to the client
    httpd = make_server(
        'localhost',  # The host name.
        8000,  # A port number where to wait for the request.
        application  # Our application object name, in this case a function.
    )

    httpd.serve_forever()